package com.blockmeta.bbs.minemodule.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.AppUtils;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.baselibrary.utils.SecurityUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.eventbus.MsgSuccess;
import com.blockmeta.bbs.businesslibrary.launch.contactusYMAL;
import com.blockmeta.bbs.businesslibrary.pojo.ContactUSPOJO;
import com.blockmeta.bbs.businesslibrary.umeng.ScreenShotUtil;
import com.blockmeta.bbs.businesslibrary.umeng.ShareRouter;
import com.blockmeta.bbs.businesslibrary.umeng.ShareType;
import com.blockmeta.bbs.businesslibrary.umeng.SharedUtils;
import com.blockmeta.bbs.businesslibrary.umeng.TypeDescribe;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.DeviceUtil;
import com.blockmeta.bbs.businesslibrary.widget.WebViewContainer;
import com.blockmeta.bbs.minemodule.R;
import com.blockmeta.bbs.minemodule.R2;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by author on 2018/2/12.
 */
@Route(path = RouterPath.HTML_INVITE_ACTIVITY)
public class HtmlInviteActivity extends BaseActivity {
    @BindView(R2.id.center_iv)
    ImageView mCenterIv;
    @BindView(R2.id.center_title)
    TextView mCenterTitle;
    @BindView(R2.id.left_back)
    LinearLayout mLeftBack;
    @BindView(R2.id.rl_title)
    RelativeLayout mRlTitle;
    @BindView(R2.id.html5_webView)
    WebView mHtml5WebView;
    @BindView(R2.id.activity_html5)
    LinearLayout mActivityHtml5;
    @BindView(R2.id.progressBar)
    ProgressBar mProgressBar;
    @BindView(R2.id.frame)
    FrameLayout mFrame;
    private String newUrl;
    @Autowired(name = Constant.ZERO)
    public String url;
    @Autowired(name = Constant.ONE)
    public String id;
    private String mTitle;
    private String mShareUrl;
    private float mScale;
    ContactUSPOJO sContactUSPOJO = contactusYMAL.getContactUSPOJO();

    private ShareRouter mShareRouter;

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        url = getIntent().getExtras().getString(Constant.ZERO);
        id = getIntent().getExtras().getString(Constant.ONE);
        return LayoutInflater.from(mContext).inflate(R.layout.activity_html_invite, null);
    }


    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void initialize() {
        super.initialize();
        EventBus.getDefault().register(this);
        WebSettings settings = mHtml5WebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setDomStorageEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        //缩放操作
        settings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        settings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        settings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //重写UserAgent
        String userAgentString = settings.getUserAgentString();
        settings.setUserAgent(userAgentString + "/"+BaseApp.getApplicationId()+"/" + AppUtils.getAppVersionName() + "(" + AppUtils.getAppVersionCode() + ")");

        String token = AccountHelper.getToken();
        if (TextUtils.isEmpty(token)){
            token = SharedPreferenceUtil.getString(mContext, Constant.TOKEN, "");
        }
        synCookies(mContext, url, "token =" + token);

        mHtml5WebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                if (mProgressBar != null) {
                    mProgressBar.setVisibility(View.GONE);
                }
                super.onPageFinished(webView, s);

                if (newUrl != null ) {
                    if (s.replace("https","http").equals(newUrl)){
                        Bitmap bitmap = captureWebView();
                        //缩放至宽固定的大小
                        final Bitmap zoomBitmap = ScreenShotUtil.zoomImg(bitmap, 1080);
                        ShareRouter shareRouter = new ShareRouter.Builder()
                                .context(mContext)
                                .shareType(ShareType.INVITE)
                                .displayBitmap(zoomBitmap)
                                .umShareListener(mUMShareListener)
                                .build();
                        shareRouter.show();
                    }
                }

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                if (s.startsWith("btc8imgshare")) {
                    //说明用户点击复制链接
                    //友盟自定义事件统计（链接分享）
                    MobclickAgent.onEvent(mContext, Constant.INVITE_LINK);
                    newUrl = s.replace("btc8imgshare", "http").trim();
                    Uri uri = Uri.parse(newUrl.replace("/#", ""));
                    String scaleStr = uri.getQueryParameter("scale");
                    if (!TextUtils.isEmpty(scaleStr)) {
                        mScale = Float.valueOf(scaleStr);
                    }
                    webView.loadUrl(newUrl);
                } else if (s.startsWith("btc8outside")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(s.replace("btc8outside", "http").trim()));
                    if (intent.resolveActivity(mContext.getPackageManager()) != null) {
                        startActivity(intent);
                    }
                } else if (s.startsWith("btc8share")) {
                    //友盟自定义事件统计（链接分享）
                    MobclickAgent.onEvent(mContext, Constant.INVITE_LINK);
                    setShare(s);
                } else {
                    webView.loadUrl(s);
                }
                return true;
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
//                super.onReceivedSslError(webView, sslErrorHandler, sslError);
                //接受SSL证书 不处理默认不接收
                sslErrorHandler.proceed();
            }
        });

        mHtml5WebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView webView, int i) {
                if (mProgressBar != null) {
                    if (i == 100) {
                        mProgressBar.setVisibility(View.GONE);
                    } else {
                        if (mProgressBar.getVisibility() == View.GONE) {
                            mProgressBar.setVisibility(View.VISIBLE);
                        }
                        mProgressBar.setProgress(i);
                    }

                    if (mListener != null) {
                        mListener.onProgressChange(webView, i);
                    }
                }
                super.onProgressChanged(webView, i);
            }

            @Override
            public void onReceivedTitle(WebView webView, String title) {
                //这里能获取到webView加载页面的标题,然后判断title是否包含指定的信息
                mTitle = title;
                if (!TextUtils.isEmpty(mTitle)&&mCenterTitle!=null){
                    mCenterTitle.setText(mTitle);
                }
                super.onReceivedTitle(webView, title);
            }


        });

        mHtml5WebView.loadUrl(url);
    }

    @Override
    protected void onDestroy() {
        try {
            mHtml5WebView.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 设置Cookie
     */

    private void setShare(String url) {
        mShareUrl = url.replace("btc8share://", "http://");
        Uri shareUri = Uri.parse(Uri.decode(mShareUrl));
        String title = shareUri.getQueryParameter("title");
        String desc = shareUri.getQueryParameter("desc");
        if (mShareRouter == null){
            mShareRouter = new ShareRouter.Builder()
                    .context(mContext)
                    .shareType(ShareType.NORMAL_WEB)
                    .typeDescribe(TypeDescribe.ACTIVITY)
                    .url(mShareUrl)
                    .title(TextUtils.isEmpty(title)?sContactUSPOJO.getActivitydesc().getTitle():title)
                    .describe(TextUtils.isEmpty(desc)?sContactUSPOJO.getActivitydesc().getDesc():desc)
                    .umShareListener(mUMShareListener)
                    .build();
        }
        mShareRouter.show();
    }

    public void synCookies(Context context, String url, String cookie) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        //cookies是在HttpClient中获得的cookie
        if (!TextUtils.isEmpty(cookie)) {
            cookieManager.setCookie(url, cookie);
        }
        String uid = AccountHelper.getUid();
        if (!TextUtils.isEmpty(uid)) {
            cookieManager.setCookie(url, "uid=" + uid);
        }else {
            cookieManager.setCookie(url, "uid=");
        }
        String token = AccountHelper.getToken();
        if (TextUtils.isEmpty(token)){
            token = SharedPreferenceUtil.getString(mContext, Constant.TOKEN, "");
        }
        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(uid)) {
            String currentTime = FormatUtil.getTimetoHMS(System.currentTimeMillis(), "yyyyMMdd");
            final String md5 = SecurityUtil.MD5(currentTime + "_eCM1_appcooike");
            cookieManager.setCookie(url, md5 + "=" + token);
            cookieManager.setCookie(url, "token=" + token);
        }else {
            cookieManager.setCookie(url, "token=");
        }

        String deviceId = DeviceUtil.getIMEI();
        if (!TextUtils.isEmpty(deviceId)) {
            cookieManager.setCookie(url, "device_id=" + deviceId);
        }
        if (!TextUtils.equals("0",id)) {
            cookieManager.setCookie(url, "activityid=" + id);
        }else {
            cookieManager.setCookie(url, "activityid=");

        }
        CookieSyncManager.getInstance().sync();
    }

    /**
     * 清楚Cookie
     */
    /**
     * 清除Cookie
     *
     * @param context
     */
    public static void removeCookie(Context context) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        CookieSyncManager.getInstance().sync();
    }

    //登入信息改变
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEvent(MsgSuccess message) {
        mHtml5WebView.post(new Runnable() {
                @Override
                public void run() {
                    synCookies(mContext, url, "");
                    mHtml5WebView.reload();
                }
            });
    }

    //    网络链接改变，需要刷新
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEvent(WebViewContainer.NetChangeEvent event) {
        if (event.m_hasConnected) {
            mHtml5WebView.reload();
        }
    }


    private onWebViewListener mListener;


    @JavascriptInterface
    private void inputJs() {
        String shareSuccess = "javascript:shareCb()";
        mHtml5WebView.loadUrl(shareSuccess);
        //需要重新LoadUrl
        mHtml5WebView.reload();
    }

    UMShareListener mUMShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA share_media) {
            inputJs();
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {

        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {

        }
    };

    //进度回调接口
    public interface onWebViewListener {
        void onProgressChange(WebView view, int newProgress);

        void onPageFinish(WebView view);
    }


    @OnClick(R2.id.left_back)
    public void onViewClicked() {
        if (mHtml5WebView.canGoBack()) {
            mHtml5WebView.goBack();
        } else {
            removeCookie(mContext);
            finish();
        }
    }

    /**
     * 对WebView进行截屏
     */
    private Bitmap captureWebView() {
        Picture picture = mHtml5WebView.capturePicture();
        int width = picture.getWidth();
        int height = picture.getHeight();
        int realHeight = (int) (mScale * width);
        if (realHeight != 0) {
            height = realHeight;
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        picture.draw(canvas);
        return bitmap;
    }
}
